package samsung.sds.menuManagement.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import samsung.sds.menuManagement.dao.MenuManagementMapper;
import samsung.sds.menuManagement.model.MenuEntity;
import samsung.sds.menuManagement.service.MenuManagementService;
import samsung.sds.system.common.baseQuery.AbstractBaseService;
import samsung.sds.system.common.baseQuery.BaseMapper;
import samsung.sds.system.common.model.QueryParam;
import samsung.sds.system.utils.CommonTools;

/**
 * @author hao.wen
 * @createDate 2016-02-23 menuManagement的service组件实现
 */
@Service
public class MenuManagementServiceImpl extends AbstractBaseService<MenuEntity>
		implements MenuManagementService {

	// 缓存菜单列表
	private Map<String, List<MenuEntity>> menuCache = new HashMap<String, List<MenuEntity>>();

	@Autowired
	private MenuManagementMapper menuManagementMapper;

	protected BaseMapper<MenuEntity> getMapper() {

		return null;
	}

	public Map<String, List<MenuEntity>> getMenuCache() {
		return menuCache;
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	public List<MenuEntity> queryList(QueryParam param) {
		String username = CommonTools.getLoginOrAnonymousUserName();
		List<MenuEntity> menuList = new ArrayList<MenuEntity>();
		// 获取request对象
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession();
		List<String> userRoleList = (List<String>) session
				.getAttribute(username);
		String userRoles = dealWithList(userRoleList);
		// 如果缓存中存在则返回，否则查询数据库并放入缓存
		if (menuCache.containsKey(userRoles)) {
			return menuCache.get(userRoles);
		} else {
			menuList = menuManagementMapper.queryMenuList(username);
			dealWithMenuList(menuList);
		}
		menuCache.put(userRoles, menuList);
		return menuList;
	}

	/**
	 * 处理menuList
	 */
	public void dealWithMenuList(List<MenuEntity> menuList) {
		String rootId = menuManagementMapper.selectRootId();
		for (int i = 0; i < menuList.size(); i++) {
			if (menuList.get(i).getMenuName().equals("待投票")) {
				Map<String, String> params1 = new HashMap<String, String>();
				params1.put("type", "wait");
				menuList.get(i).setParams(params1);
			}

			if (menuList.get(i).getMenuName().equals("已投票")) {
				Map<String, String> params2 = new HashMap<String, String>();
				params2.put("type", "alreadyVoted");
				menuList.get(i).setParams(params2);
			}

			if (menuList.get(i).getMenuName().equals("已结束")) {
				Map<String, String> params3 = new HashMap<String, String>();
				params3.put("type", "finished");
				menuList.get(i).setParams(params3);
			}

			int level = 0;
			String parentId = menuList.get(i).getParentId();
			if (menuList.get(i).getParentId().equals(rootId)) {
				menuList.get(i).setLevel(0);
			} else {
				while (menuList.get(i).getParentId() != rootId) {

					String pId = menuManagementMapper.queryLevel(parentId);
					parentId = pId;
					level++;
					if (pId.equals(rootId)) {
						break;
					}
				}
				menuList.get(i).setLevel(level);
			}
			menuList.get(i).setRequestType("post");
		}
	}

	/**
	 * 处理UserRoles
	 * 
	 * @param list
	 * @return
	 */
	private String dealWithList(List<String> list) {
		StringBuffer stringBuffer = new StringBuffer();
		for (String userRole : list) {
			stringBuffer.append(userRole).append(",");
		}
		return stringBuffer.length() > 0 ? stringBuffer.substring(0,
				stringBuffer.length() - 1) : stringBuffer.toString();
	}

	@Override
	public List<MenuEntity> queryMenuTree() {
		return menuManagementMapper.queryMenuTree();
	}

	@Override
	public List<MenuEntity> queryDetail(String menuId) {
		return menuManagementMapper.queryDetail(menuId);
	}

	/** 获取左边角色 */
	@Override
	public List<MenuEntity> queryRoles(String menuId) {
		return menuManagementMapper.queryRoles(menuId);
	}

	/** 删除逻辑 */
	@Override
	public int deleteMenu(String menuId) {
		int result = 0;
		// delete role
		menuManagementMapper.deleteMenuRole(menuId);

		menuManagementMapper.deleteMenu(menuId);
		updateCache();
		return result;
	}

	/**
	 * 新建菜单及角色
	 */
	@Override
	public int insertEntity(MenuEntity menuentity) {

		int result = menuManagementMapper.insertMenu(menuentity);
		if (menuentity.getRole() != null && menuentity.getRole() != "") {

			String[] roleArray = menuentity.getRole().split(",");
			for (String i : roleArray) {
				menuentity.setRole(i);
				menuManagementMapper.insertMenuRole(menuentity);
			}
		}
		updateCache();
		return result;
	}

	/* 更新逻辑 */
	@Override
	public int updateEntity(MenuEntity menuentity) {

		int result = 0;
		result = menuManagementMapper.updateMenu(menuentity);
		if (menuentity.getRole() != null && menuentity.getRole() != "") {
			menuManagementMapper.deleteMenuRole(menuentity.getId());
			String[] roleArray = menuentity.getRole().split(",");
			for (String i : roleArray) {
				menuentity.setRole(i);
				menuManagementMapper.insertMenuRole(menuentity);
			}
		}
		updateCache();
		return result;
	}

	/**
	 * 更新缓存
	 */
	@Override
	public void updateCache() {
		for (Entry<String, List<MenuEntity>> entry : menuCache.entrySet()) {
			String roles = entry.getKey();
			String dealWithedRoles = dealWithRoles(roles);
			List<MenuEntity> menuEntities = menuManagementMapper
					.queryMenuListByRoles(dealWithedRoles);
			dealWithMenuList(menuEntities);
			menuCache.put(roles, menuEntities);
		}

	}

	/**
	 * 处理角色信息
	 * 
	 * @param roles
	 * @return
	 */
	private String dealWithRoles(String roles) {
		StringBuffer stringBuffer = new StringBuffer();
		String[] roleArray = roles.split(",");
		for (String tempStr : roleArray) {
			stringBuffer.append("'").append(tempStr).append("'").append(",");
		}
		return stringBuffer.length() > 0 ? stringBuffer.substring(0,
				stringBuffer.length() - 1) : stringBuffer.toString();
	}

}